package Server;

import java.awt.RenderingHints.Key;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.Runnable;
import java.net.Socket;


import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;

public class ConnectionHandler implements Runnable {

	public Socket socket;
	private ChatterServer server;
	private DH alice;
	private KeyAgreement kaa;

	

	
	public ConnectionHandler(Socket socket, ChatterServer cs)
	{
		this.socket = socket;
		server = cs;
	}


	public void exchangeKeys() throws Exception 
	{
		ObjectOutputStream output;
		ObjectInputStream input;
		DHParameterSpec msg;
		java.security.Key msg2;
		try {
			
			alice = new DH(DH.USE_DEF_DH_PARAMS);
			
			output = new ObjectOutputStream(socket.getOutputStream());
			input = new ObjectInputStream(socket.getInputStream());
			
			msg = alice.getDHPublicKey().getParams();
			output.writeObject(msg.getG());
			output.writeInt(msg.getL());
			output.writeObject(msg.getP());
			kaa = alice.getDHKeyAgreement();
			
			msg2 = (java.security.Key) input.readObject();
			kaa.doPhase(msg2,true);
			
			msg2 = alice.getDHPublicKey();
			output.writeObject(msg2);
			
			testKeys();
			//authenticate();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	public void authenticate(String username, String password) 
	{
		boolean validate = DBComm.ValidateUser(username,password);
		
	}


	public void testKeys()
	{
		System.out.println("in testkeys");
		ObjectOutputStream output;
		byte[] msg = kaa.generateSecret();
		try {
			output = new ObjectOutputStream(socket.getOutputStream());
			output.writeObject(msg);
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void run() 
	{
		try {
			exchangeKeys();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	


	
}
